package
{
import com.societyGames.codeAlong.LoadingText;

import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;

[SWF(width="1024", height="768", frameRate="30", backgroundColor="#FFFFFF")]
public class Preloader extends MovieClip
{
  private var _loadingText:LoadingText;

  public function Preloader()
  {
    stop();
    createInterface();
    initializeStage();
    addEventListener(Event.ENTER_FRAME, onEnterFrame);
  }

  private function createInterface():void
  {
    this._loadingText = new LoadingText();
    this.addChild(this._loadingText);
  }

  private function initializeStage():void
  {
    this.stage.align = StageAlign.TOP_LEFT;
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.addEventListener(Event.RESIZE, stageResizeHandler);
    stageResizeHandler(null);
  }

  private function stageResizeHandler(event:Event):void
  {
    _loadingText.width = stage.stageWidth;
    _loadingText.height = stage.stageHeight;
  }

  public function onEnterFrame(event:Event):void
  {
    //We're done loading.
    if (framesLoaded == totalFrames)
    {
      removeEventListener(Event.ENTER_FRAME, onEnterFrame);
      nextFrame();
      loadMainClass();
      this.removeChild(this._loadingText);
    }
    else
    {
      //var percent:Number = (stage.loaderInfo.bytesLoaded / stage.loaderInfo.bytesTotal) * 100;
      //this._loadingText.text = "Loading: " + percent + "%";
    }
  }

  private function loadMainClass():void
  {
    //if class is inside package you'll have use full path ex.org.actionscript.Main
    var mainClass:Class = Class(getDefinitionByName("CodeAlong"));
    if (mainClass)
    {
      var displayObject:DisplayObject = DisplayObject(new mainClass());
      addChild(displayObject);
    }
  }
}
}